/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-11-24     86159       the first version
 */

#include"sem.h"
void th11_entry(void *parameter)
{
    while(1)
    {
        rt_thread_mdelay(2000);
        rt_sem_take(sem1, RT_WAITING_FOREVER);
        flags++;
        if(flags==100)
        {
            flags=0;
        }
        rt_kprintf("th11_entry [%d]\n",flags);
        rt_sem_release(&sem2);

    }

}

void th22_entry(void *parameter)
{
    rt_sem_take(&sem2, RT_WAITING_FOREVER);
    if(flags>0)
    {
        flags--;
    }
    rt_kprintf("th22_entry [%d]\n",flags);
    rt_sem_release(sem1);
    rt_thread_mdelay(2000);
}

int sem(void)
{
    //动态创建信号量
    sem1=rt_sem_create("sem1", 1, RT_IPC_FLAG_FIFO);//名字设置时<=8
    if(sem1==RT_NULL)
    {
           LOG_E("sem1 rt_sem_creat faile...\n");
           return -ENOMEM;
     }
     LOG_D("sem1 rt_sem_creat successed...\n");
     //静态创建信号量
     int ret=0;
     ret=rt_sem_init(&sem2, "sem2", 0, RT_IPC_FLAG_FIFO);
     if(ret<0)
     {
            LOG_E("sem2 rt_sem_init faile...\n");
            return -ENOMEM;
      }
      LOG_D("sem2 rt_sem_init successed...\n");

      th111=rt_thread_create("th1", th11_entry, NULL, 512, 20, 5);
      if(th111==NULL)
      {
            LOG_E("th1 rt_thread_create faile...\n");
            return -ENOMEM;
       }
       LOG_D("th1 rt_thread_create successed...\n");
       th222=rt_thread_create("th2", th22_entry, NULL, 512, 20, 5);
       if(th222==NULL)
       {
            LOG_E("th2 rt_thread_create faile...\n");
            return -ENOMEM;
        }
        LOG_D("th2 rt_thread_create successed...\n");
        rt_thread_startup(th111);
        rt_thread_startup(th222);
        return 0;
}
